package com.xxwy.simple;

import com.xxwy.pb.MyDataInfo;
import io.netty.buffer.ByteBuf;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.ChannelInboundHandlerAdapter;
import io.netty.util.CharsetUtil;

/**
 * @author wy
 * @date 2020/3/4 23:16
 */
public class NettyClientHandler extends ChannelInboundHandlerAdapter {

  /**
   * 通道就绪触发的事件
   * 添加编码
   *
   * @param ctx
   * @throws Exception
   */
  @Override
  public void channelActive(ChannelHandlerContext ctx) throws Exception {
    //StudentPOJO.Student xxwy = StudentPOJO.Student.newBuilder().setId(1).setName("xxwy").build();
    //ctx.writeAndFlush(Unpooled.copiedBuffer("hello server", CharsetUtil.UTF_8));

    //创建一个学生
    MyDataInfo.Student.Builder xxwy = MyDataInfo.Student.newBuilder().setName("XXWY").setId(51);
    MyDataInfo.MyMessage messageStudent = MyDataInfo.MyMessage.newBuilder()
        .setDataType(MyDataInfo.MyMessage.DataType.StudentType)
        .setStudent(xxwy).build();

    //创建一个work
    MyDataInfo.Worker.Builder work = MyDataInfo.Worker.newBuilder().setName("XXWY").setAge(15);
    MyDataInfo.MyMessage messageWork = MyDataInfo.MyMessage.newBuilder()
        .setDataType(MyDataInfo.MyMessage.DataType.WorkType)
        .setWorker(work).build();
    ctx.writeAndFlush(messageWork);
  }

  /**
   * @param ctx
   * @param msg
   * @throws Exception
   */
  @Override
  public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception {
    ByteBuf buf = (ByteBuf) msg;
    System.out.println("server：" + buf.toString(CharsetUtil.UTF_8));

  }


  @Override
  public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception {
    cause.printStackTrace();
    ctx.close();
  }
}
